/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2015-02-04 10:50:44
 * @filename : static/site/nff/controller/emailList.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){
    require('{component}promptTip/promptTip.css');
    var EmailListView, mId = 'emailList', reRender = false, menuName = 'email',
        scrollTop = 0, scrollAjax = true, searchBool = false,emailType = '.Inbox',emailName='Emails',
        
        condition = {
            page    : 0,
            from    : 0,
            offset  : 20
        },

        searchCondition = {
            page    : 0,
            from    : 0,
            offset  : 20
        },

        panel = require('{component}panel/zepto.panel'),
        promptTip = require('{component}promptTip/promptTip'),
        imglazyload = require('{component}imglazyload/zepto.imglazyload'),
        tplN = require('{view}userNav.tpl'),
        tplM = require('{view}folderNull.tpl'),
        tpl = require('{view}emailList.tpl'),
        tplL = require('{view}emailListLi.tpl');

    EmailListView = Backbone.View.extend({

        el: 'body',

        template: _.template(tpl),
        templateN: _.template(tplN),
        templateL: _.template(tplL),
        templateM: _.template(tplM),

        initialize: function () {
        },

        bindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            dom.find('.body_all').on('touchstart',function(){
                var input = dom.find('input');
                    input.blur();
            });
 
            dom.find('.left').on('tap',function(e){
                share.blur(mId); 
                if (panel.info.state == 'hidden') {
                    panel.show();
                } else {
                    panel.hidden();
                }
            });
          
            dom.find('.right').on('tap',function(e){
                window.location.href = '#emailNav/whole/custom'+emailType+'##'+emailName; 
            });

            dom.find('.sendBox').on('tap',function() {
                tthis.toggleSearch(true); 
            });

            dom.find('.body_all_bg').on('touchstart touchmove',function(e) {
                e.stopPropagation();
                e.preventDefault(); 
            });

            dom.find('input').keypress(function(e){
                 if (e.keyCode == 13) {
                     dom.find('input').blur();   
                     searchBool = true;
                     dom.find('.body_all_bg').css({display:'none'});
                     dom.find('.emailDefault').css({display:'none'});
                     dom.find('.emailSearch').css({display:'block'});
                     searchCondition.keyword = dom.find('.inputSearch').val();
                     tthis.ajaxList(searchCondition); 
                 } 
            });

            dom.find('.cancel').on('tap',function(e) {
                e.stopPropagation();
                e.preventDefault(); 
                searchBool = false;
                tthis.resetSearch();
                tthis.toggleSearch(false); 
            });

            $(window).on('scroll.'+mId,function(e){
                if(seajs.moduleUI == mId) {
                    var WH = $(window).height(),
                        SH = $(window).scrollTop(),
                        DH = $('#'+mId).height();

                    scrollTop = SH;    
                    if (SH > 0 && (DH-WH-SH) < 100) { 
                        var data =  searchBool ? searchCondition : condition;
                        tthis.ajaxList(data);
                    }
                    dom.find('.body_all').imglazyload({startY : SH,endY:SH + $(window).height()});
                }
            });
            /*
            dom.find('.emailList').on('touchstart',function(e) {
                var li = $(e.target).closest('li');
                $(li).css('background','#ccc');
            });
            */
            dom.find('.emailList').on('touchstart',function(e) {
                $(this).find('li').css('background','transparent');           
                var li = $(e.target).closest('li');
                li.css('background','#D5DDE0');           
            }).on('touchend',function(e){
                var li = $(e.target).closest('li');
                li.css('background','transparent');           
            });
            dom.find('.emailList').on('tap',function(e) {
                var eid = $(e.target).closest('.info').attr('eid');
                if (eid) {
                    $(e.target).closest('.info').find('.read_icon').remove();
                    if (emailType == '.Draft') {
                        window.location.href = '#compose/whole/custom'+JSON.stringify({type:'draft',eid:eid,emailType:emailType,emailName:emailName}); 
                    } else {
                        window.location.href = '#readEmail/whole/custom'+eid+'##'+emailType+'##'+emailName; 
                    }
                }
            });
            dom.find('.emailList').on('tap',function(e) {
                var uid = $(e.target).closest('label').attr('uid'),
                    userName = $(e.target).closest('label').attr('username');
                if (uid) {
                    if ($(window).height() < 640) {
                        if (panel.info.state == 'hidden') {
                            window.location.href = '#userProfile/whole/custom'+uid+'&&'+userName; 
                        }
                    } else {
                        window.location.href = '#userProfile/whole/custom'+uid+'&&'+userName; 
                    }
                }
            });
            dom.find('.sendFixedButton').on('tap',function(){
                var obj = {
                        type : 'create',
                        emailType :emailType,
                        emailName :emailName
                    };
                window.location.href = '#compose/whole/custom'+JSON.stringify(obj); 
            });
        },      

        toggleSearch : function(bool) {
            var dom = $('#'+mId),
                that = dom.find('.sendBox');
            if (bool) {
                that.css({'margin-right':'80px'});
                that.find('.inputBox').css({width:'auto'});
                that.find('.cancel').css({display:'block'});
                that.find('input').removeAttr('disabled').focus();
                dom.find('.body_all_bg').css({display:'block'});
            } else {
                that.css({'margin-right':'0'});
                that.find('.inputBox').css({width:'150px'});
                that.find('.cancel').css({display:'none'});
                that.find('input').val('').attr('disabled',true).blur();
                dom.find('.body_all_bg').css({display:'none'});
                dom.find('.emailDefault').css({display:'block'});
                dom.find('.emailSearch').css({display:'none'}).html('');
            }
        },
 
        defaultData : function() {
            condition = {
                page    : 0,
                from    : 0,
                offset  : 20
            }
            this.resetSearch();
        }, 

        resetSearch : function() {
            scrollTop = 0, 
            scrollAjax = true,
            searchCondition = {
                page    : 0,
                from    : 0,
                offset  : 20,
                keyword : '',
            };
        },

        render: function (obj) {
            if (!share.checkPermission(true)){return;};
            share.reRender(reRender,mId);
            var arr = (obj.val) ? obj.val.split('##') : [];    
            if (emailType !== arr[0]) {
                share.reRender(true,mId);
                this.defaultData(); 
            }

            if ($('#'+mId).length < 1) { 
                $('body').append(this.template(lang)); 
                this.bindEvt();
                var wHeight = $(window).height(),
                    headH = $('#'+mId).find('.head').height(),
                    searchH = $('#'+mId).find('.emailFixedSearch').height();
                $('#'+mId).find('.body_all').css({'min-height':wHeight-headH-searchH+'px'});
            } else {
                $('#'+mId).css('display','block');
            }

            share.panel(panel,this.templateN,mId,menuName,this.panelCallBack);

            this.emailType(obj);

            var dom = $('#'+mId).find('.body_all').find('ul');
                if (dom.find('li').length < 1) {
                    this.ajaxList(condition); 
                } else {
                    (function(y){
                        setTimeout(function() {
                           window.scroll(0,y);
                        },10);
                    })(scrollTop);
                }
        },

        emailType : function(obj) {
             if (obj.val) {
                 var arr = obj.val.split('##');             
                 emailType = arr[0];
                 emailName = arr[1];
             } else {
                 emailType = '.Inbox';
                 emailName = 'Emails';
             }
             $('#'+mId).find('.head').find('.title').html(emailName);  
        }, 

        panelCallBack : function(obj) {
              var dom = $('#'+mId);
              if (util.deviceSize()) { 
                  if (obj.state == 'hidden') {
                    setTimeout(function() {
                        dom.find('.sendFixedButton').css('display','block');
                    },500);
                  } else {
                    dom.find('.sendFixedButton').css('display','none');
                  }
              } else {
                  dom.find('.sendFixedButton').css('position','fixed');
              }
        },

        countNum : function(count) {
              if (count > 0 ) {
                  $('#'+mId).find('.num').html(count).css('display','inline'); 
              } else  {
                  $('#'+mId).find('.num').html('').css('display','none');
              } 
        },

        ajaxList : function(data) {
            data.subfolder = emailType; 
            var tthis = this,
                dom =  searchBool ? $('#'+mId).find('.body_all').find('.emailSearch') : $('#'+mId).find('.body_all').find('.emailDefault');
            var obj = {
                url : seajs.data.vars.apiAccessUrl+'wm_get_folder',
                type : 'POST',
                data : data,
                success : function(data) {
                    if (data.ret) {
                        //tthis.countNum(data.count); 
                        var Img = seajs.data.vars.resourceUrl+'img/';
                        var list = data.list;
                        if(list.length < 1 && dom.find('li').length < 1) {
                            //dom.html(tthis.templateM());
                            var str = searchBool ? 'There are no emails/winks in this folder! Browse your matches and email someone now.' :'There are no emails/winks in this folder!';
                            promptTip.show({type:'noData',text:str, dom:dom});
                            return; 
                        } else {
                            if (searchBool) {
                               searchCondition['page']++;
                               searchCondition['from'] = searchCondition['page'] * searchCondition['offset'];
                            } else {
                               condition['page']++;
                               condition['from'] = condition['page'] * condition['offset'];
                            }
                            dom.append(tthis.templateL({arr:list,defaultImg:Img,user:data.info}));
                            dom.imglazyload({startY : 0,endY: $(window).height()}); 
                        }
                     }
                },
                error : function(xhr, errorType, error) {},
                complete : function(xhr, status) {
                    share.ajaxEndB($('#'+mId).find('ul'));
                    setTimeout(function(){
                        scrollAjax = true;
                    },500)
                }
            }
            
            if (scrollAjax) {
                scrollAjax = false;
                promptTip.hide({type:'noData', dom:dom});
                share.ajaxStartB(dom);
                (function(tthis,dom){
                    $.ajax(share.ajaxControl(obj));
                })(tthis,dom);
            }
        },

	});

	module.exports = EmailListView;
})

